package com.soecode.lyf.web;


import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpSession;

import org.apache.http.util.TextUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.github.pagehelper.PageHelper;
import com.soecode.lyf.config.JWTUtils;
import com.soecode.lyf.config.MD5Utils;
import com.soecode.lyf.config.SmsUtil;
import com.soecode.lyf.dto.Result;
import com.soecode.lyf.entity.Book;
import com.soecode.lyf.entity.Comment;
import com.soecode.lyf.entity.Msg;
import com.soecode.lyf.entity.User;
import com.soecode.lyf.entity.UserInfo;
import com.soecode.lyf.service.UserService;

import net.sf.json.JSONArray;


@Controller
// @Scope("session") // 表示会话级别
@RequestMapping("/user") // url:/模块/资源/{id}/细分 /seckill/list
public class UserController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserService userService;
    private Map<String, String> map = new HashMap();

    final int ERROR = 1;
    final int SUCCESS = 0;

    @ResponseBody
    @RequestMapping(value = "messagecode", method = RequestMethod.GET)
    public Result messagecode(String username) {
        System.out.println("请求进来了获取到了用户名" + username);
        String reg = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$"; //手机验证
        Pattern pattern = Pattern.compile(reg);//编译正则
        Matcher matcher = pattern.matcher(username);//手机验证用户名是否匹配正则(手机号)
        boolean rs = matcher.find();//手机用户名(手机号)
        Result result = null;
        if (StringUtils.isEmpty(username)) {
            result = new Result(1, "用户名不能为空");
        } else if (rs == true) { // 手机号匹配正则，才发验证码
            int code = (int) ((Math.random() * 9 + 1) * 1000);//生成四位随机数，当验证码
            SmsUtil smsUtil = new SmsUtil();
            Msg msg = smsUtil.sendMsg(username, code);
            map.put(username, Integer.toString(code));
            System.out.println("验证码发送成功" + code);
            result = new Result(0, "验证码发送成功");
        } else {
            result = new Result(0, "请输入正确的手机号");
        }
        return result;
    }

    ;

    public boolean compare(String time1, String time2) throws ParseException {
        //如果想比较日期则写成"yyyy-MM-dd"就可以了
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //将字符串形式的时间转化为Date类型的时间
        Date a = sdf.parse(time1);
        Date b = sdf.parse(time2);
        //Date类的一个方法，如果a早于b返回true，否则返回false
        if (a.before(b))
            return true;
        else
            return false;
    }

    @ResponseBody
    @RequestMapping(value = "register", method = RequestMethod.GET)
    public Result register(String msgcode, String password, String username) throws Exception {
        System.out.println("注册请求进来" + "验证码:" + msgcode + "密码:" + password);
        String regex = "^(?!.*\\s)(?!\\d{1,9}$).{6,16}$";//密码验证
        Pattern pattern = Pattern.compile(regex);//编译正则
        Matcher matcherpwd = pattern.matcher(password);//手机验证密码是否匹配正则(6-16个字符 不能包含空格 不能是9位以下纯数字)
        boolean rspwd = matcherpwd.find();//手机密码(6-16个字符 不能包含空格 不能是9位以下纯数字)
        Result result = null;
        if (map.containsKey(username)) { // 看看map集合中的指定key是否存在
            String code = map.get(username);
            if (msgcode.equals(code) && rspwd) {
                // 注册之前先查询一下数据库，看是否已经注册
                User userIsExist = isExist(username);
                System.out.println("看看查询的结果" + userIsExist);
                if (userIsExist == null) { // 不存在(没注册过)
                    String md5_pwd = MD5Utils.md5(password);
                    String[] a = {"http://120.79.178.165:8080/docs/upload/mrone.jpg", "http://120.79.178.165:8080/docs/upload/mrtwo.jpg", "http://120.79.178.165:8080/docs/upload/mrtrhee.jpg", "http://120.79.178.165:8080/docs/upload/mrfour.jpg", "http://120.79.178.165:8080/docs/upload/mrfive.jpg", "http://120.79.178.165:8080/docs/upload/mrsix.jpg"};
                    int index = (int) (Math.random() * a.length);
                    String imgpath = a[index];
                    int indexnum = (int) ((Math.random() * 9 + 1) * 10000);
                    String end = String.valueOf(indexnum);
                    String nickname = "知客" + "_" + end;
                    Date birthday1 = new Date();
                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String birthday = df.format(birthday1);
                    UUID uuid = UUID.randomUUID();
                    JWTUtils jwt = new JWTUtils();
                    String token = jwt.createToken(uuid.toString());// 加密生成token
                    Calendar nowTime = Calendar.getInstance();
                    nowTime.add(Calendar.HOUR, 24 * 7);
                    Date experiesDate = nowTime.getTime(); // 设置token有效期(7天)
                    //DecodedJWT login = jwt.verifyToken(token); // 解密
                    String exp = df.format(experiesDate); // TOKEN有效期7天后的日期
                    int i = userService.Register(uuid.toString(), nickname, md5_pwd, imgpath, username, birthday, token, exp);
                    System.out.println("看看注册后的i值" + i);
                    if (i == 0) {
                        result = new Result(1, "注册失败");
                    } else {
                        map.remove(username);
                        result = new Result(0, "注册成功");
                    }
                } else {
                    result = new Result(1, "该手机号已被注册！");
                }
            } else if (!msgcode.equals(code)) {
                result = new Result(1, "验证码错误");
            } else if (!rspwd) {
                result = new Result(1, "密码不符合格式");
            }
        }
        return result;
    }

    public User isExist(String username) { // 判断用户是否在数据库中存在
        User uu = userService.SelectUser(username);
        return uu;
    }

    @ResponseBody
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public Result login(String username, String password, Model model) throws Exception {
        Result result = new Result();
        System.out.println("获取到登录信息" + username + "密码:" + password);
        if (StringUtils.isEmpty(username) && StringUtils.isEmpty(password)) {
            result = new Result(1, "用户名密码不能为空");
            System.out.println("1");
        } else {
            System.out.println("2");
            String md5_pass = MD5Utils.md5(password);
            UserInfo userinfo = userService.login(username, md5_pass);
            System.out.println("登录后" + userinfo);
            if (userinfo != null) {
                JWTUtils jwt = new JWTUtils();
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String Token = jwt.createToken(userinfo.getId());// 生成token
                Calendar nowTime = Calendar.getInstance();
                nowTime.add(Calendar.HOUR, 24 * 7);
                Date experiesDate = nowTime.getTime(); // 设置token有效期(7天)
                //DecodedJWT login = jwt.verifyToken(token); // 解密
                String exp = df.format(experiesDate); // TOKEN有效期7天后的日期
                int i = userService.UpdateTokenExp(username, md5_pass, exp, Token);
                if (i != 0) {
                    UserInfo uu = userService.getUserInfo(userinfo.getId());
                    model.addAttribute("USERINFO", uu);
                    result = new Result(0, model, "登录成功");
                    System.out.println("登录成功返回信息" + model);
                }
            } else {
                result = new Result(1, "用户名或密码错误");
            }
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "sign", method = RequestMethod.GET)
    public Result sign(String date, String userid, Model model) throws Exception {
        Result result = new Result();
        if (!StringUtils.isEmpty(date) && !StringUtils.isEmpty(userid)) {
            Map fleg = userService.selectIsSign(userid, date);
            System.out.println("看看" + fleg);
            if (fleg == null) { // 当天未签到
                int i = userService.insertSignin(date, userid);
                result = new Result(0, "签到成功");
            } else { // 当天已签到
                model.addAttribute("sign", fleg);
                result = new Result(1, model, "当天已签到");
            }
        } else if (StringUtils.isEmpty(date)) {
            List<User> list = userService.selectSignDays(userid);
            System.out.println("签到日期列表" + list);
            model.addAttribute("signDays", list);
            result = new Result(0, model, "查询成功");
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "QQlogin", method = RequestMethod.GET)
    public Result QQlogin(String nickname, String openid, String headurl, String sex, int age, Model model) throws Exception {
        Result result = new Result();
        if (!StringUtils.isEmpty(nickname) && !StringUtils.isEmpty(openid) && !StringUtils.isEmpty(headurl) && !StringUtils.isEmpty(sex) && !StringUtils.isEmpty(age)) {
            Date birthday1 = new Date();
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String birthday = df.format(birthday1);
            JWTUtils jwt = new JWTUtils();
            String token = jwt.createToken(openid.toString());// 加密生成token
            Calendar nowTime = Calendar.getInstance();
            nowTime.add(Calendar.HOUR, 24 * 7);
            Date experiesDate = nowTime.getTime(); // 设置token有效期(7天)
            //DecodedJWT login = jwt.verifyToken(token); // 解密
            String exp = df.format(experiesDate); // TOKEN有效期7天后的日期
            UserInfo user = new UserInfo();
            user.setOpenid(openid);
            user.setAge(age);
            user.setSex(sex);
            user.setNickname(nickname);
            user.setHeadurl(headurl);
            user.setBirthday(birthday);
            user.setToken(token);
            user.setExp(exp);
            UserInfo uu = userService.getUserInfo(openid);
            if (uu == null) {
                int i = userService.QQLogin(user);
                if (i != 0) { // 登录成功
                    UserInfo uu1 = userService.getUserInfo(openid);
                    model.addAttribute("USERINFO", uu1);
                    result = new Result(0, model, "登录成功");
                } else { // 当天已签到
                    result = new Result(1, "登录失败");
                }
            } else {
                model.addAttribute("USERINFO", uu);
                result = new Result(0, model, "登录成功");
            }
        } else {
            result = new Result(1, "缺少参数");
        }
        return result;
    }
}
